package com.lzm.flash;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lzm on 2018/2/26.
 */

public class RefreshListView extends ListView implements AbsListView.OnScrollListener{

    View m_header;      //顶部的布局
    int m_headerHeight;

    int m_firstVisibleItem;  //当前第一个可见的iten的位置
    int m_scrollState;   //当前listView的滚动位置
    boolean m_isRemark;   //是在listview的最顶端按下的
    int        m_startY;  //按下时的Y值

    //当前的状态枚举

    final int    None=0; //正常状态
    final int    Pull=1;  //提示下拉转态
    final int    Release=2; //提示释放状态
    final int    Refreshing=3; //刷新状态


    int m_currState;   //当前的状态

    TextView m_tip=null;
    ImageView m_arrow=null;
    ProgressBar m_progressBar=null;
    TextView m_lastupdatetime=null;

    RotateAnimation m_animationDown=null;
    RotateAnimation m_animationUp=null;

    public interface IRefreshListener{
        public void onRefresh();
    }

    IRefreshListener m_iRefreshListener;   //刷新数据的接口


    public RefreshListView(Context context) {
        super(context);
        initView(context);
        initRotateAnimation();
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
        initRotateAnimation();

    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
        initRotateAnimation();

    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initView(context);
        initRotateAnimation();

    }

    private void initRotateAnimation()
    {
        m_animationDown=new RotateAnimation(0,180,
                RotateAnimation.RELATIVE_TO_SELF,0.5f,
                RotateAnimation.RELATIVE_TO_SELF,0.5f);
        m_animationDown.setDuration(500);
        m_animationDown.setFillAfter(true);

        m_animationUp= new RotateAnimation(180, 0,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        m_animationUp.setDuration(500);
        m_animationUp.setFillAfter(true);
    }
    //初始化  添加顶部布局到listview
    private void initView(Context context)
    {
        LayoutInflater inflater=LayoutInflater.from(context);
        m_header=inflater.inflate(R.layout.header_ref_list_view,null);
        measureView(m_header);
        m_headerHeight=m_header.getMeasuredHeight();
        topPadding(-m_headerHeight);
        this.addHeaderView(m_header);
        this.setOnScrollListener(this);


        m_tip=(TextView)m_header.findViewById(R.id.tip);
        m_arrow=(ImageView)m_header.findViewById(R.id.arrow);
        m_progressBar=(ProgressBar)m_header.findViewById(R.id.progress);
        m_lastupdatetime = (TextView) m_header.findViewById(R.id.lastupdate_time);

    }

    //通知父布局占用的宽高
    private void measureView(View view)
    {
        ViewGroup.LayoutParams p=view.getLayoutParams();
        if (p==null)
        {
            p=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int width=ViewGroup.getChildMeasureSpec(0,0,p.width);
        int hight=0;
        int tmpHight=p.height;
        if (tmpHight>0)
        {
            hight=MeasureSpec.makeMeasureSpec(tmpHight,MeasureSpec.EXACTLY);

        }else{

            hight=MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED);
        }

        view.measure(width,hight);
    }

    //设置heard布局上边距
    private void topPadding(int topPadding)
    {
        m_header.setPadding(m_header.getPaddingLeft(),topPadding,
                m_header.getPaddingRight(),m_header.getPaddingBottom());
        m_header.invalidate();
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
        m_scrollState=i;
    }

    @Override
    public void onScroll(AbsListView view,int firstVisibleItem,int visibleItemCount
            ,int totalItemCount){
        this.m_firstVisibleItem=firstVisibleItem;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction())
        {
            //按下手指
            case MotionEvent.ACTION_DOWN:
                if (m_firstVisibleItem==0)
                {
                    m_isRemark=true;
                    m_startY=(int)ev.getY();
                }
                break;

            //移动手指
            case MotionEvent.ACTION_MOVE:
                onMove(ev);
                break;

            //松开手
            case MotionEvent.ACTION_UP:
                if (m_currState==Release)
                {
                    m_currState=Refreshing;
                    //加载数据
                    refreshViewByState();
                    m_iRefreshListener.onRefresh();
                }else if (m_currState==Pull)
                {
                    //提示下拉状态 如果释放  就什么也不做
                    m_currState=None;
                    m_isRemark=false;
                    refreshViewByState();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    //判断移动过程
    private  void onMove(MotionEvent ev)
    {
        if (!m_isRemark)
            return;

        int temY=(int)ev.getY();
        int space=temY-m_startY;
        int toppadding=space-m_headerHeight;
        switch (m_currState)
        {
            case None:
                if (space>0)
                {
                    //正在下拉
                    m_currState=Pull;
                    refreshViewByState();
                }
                break;

            case Pull:
                topPadding(toppadding);
                if (space>m_headerHeight+30){
                    m_currState=Release;
                    refreshViewByState();
                }
                break;

            case Release:
                topPadding(toppadding);
                if (space<m_headerHeight+30)
                {
                    m_currState=Pull;
                    refreshViewByState();
                }
                break;
        }
    }

    //根据状态改变界面
    private void refreshViewByState(){


        switch (m_currState)
        {
            case None:
                //正常状态  不显示
                m_arrow.clearAnimation();;
                topPadding(-m_headerHeight);
                break;

            case Pull:
                //下拉状态  显示箭头，隐藏进度条
                m_arrow.setVisibility(View.VISIBLE);
                m_progressBar.setVisibility(View.GONE);
                m_tip.setText("下拉刷新");
                m_arrow.clearAnimation();
                m_arrow.setAnimation(m_animationUp);
                m_lastupdatetime.setVisibility(View.VISIBLE);
                break;

            case Release:
                m_arrow.setVisibility(View.VISIBLE);
                m_progressBar.setVisibility(View.GONE);
                m_tip.setText("松开刷新");
                m_arrow.clearAnimation();
                m_arrow.setAnimation(m_animationDown);
                m_lastupdatetime.setVisibility(View.VISIBLE);
                break;

            case Refreshing:
                topPadding(50);
                m_arrow.setVisibility(View.GONE);
                m_progressBar.setVisibility(View.VISIBLE);
                m_tip.setText("正在刷新...");
                m_arrow.clearAnimation();
                m_lastupdatetime.setVisibility(View.GONE);
        }

    }

    //获取完数据之后
    public void refreshComplete() {
        m_currState=None;
        m_isRemark = false;

        SimpleDateFormat format = new SimpleDateFormat("hh:mm");
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        m_lastupdatetime.setText("最近更新："+time);
        m_progressBar.setVisibility(View.GONE);
        m_tip.setText("刷新成功");
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                refreshViewByState();
            }
        }, 800);
    }

    //设置更新数据的接口

    public void setInterface(IRefreshListener iRefreshListener){
        this.m_iRefreshListener = iRefreshListener;
    }
}
